package com.ruanda.spongebobrunner.ui;

import android.content.Context;
import android.animation.ValueAnimator;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.util.Log;
import android.view.MotionEvent;
import com.ruanda.spongebobrunner.R;
import com.ruanda.spongebobrunner.utils.SoundUtils;

/**
 * 游戏按钮封装类
 */
public class GameButton {
    private Rect bounds;
    private String text;
    private int backgroundColor;
    private int pressedBackgroundColor;
    private int textColor;
    private int cornerRadius;
    private float textSizeSp;
    private boolean isPressed = false;
    private float scaleFactor = 1.0f;
    private ValueAnimator scaleAnimator;
    private Paint paint;
    private Paint textPaint;
    private SoundUtils soundUtils;

    public interface OnClickListener {
        void onClick();
    }

    private OnClickListener onClickListener;
    private Context context;

    private float pxFromSp(float sp) {
        return android.util.TypedValue.applyDimension(
                android.util.TypedValue.COMPLEX_UNIT_SP,
                sp,
                context.getResources().getDisplayMetrics());
    }

    public GameButton(Context context, Rect bounds) {
        this.bounds = bounds;

        // 初始化音效工具类
        soundUtils = new SoundUtils(context);

        // 加载自定义字体
        try {
            Typeface customFont = Typeface.createFromAsset(context.getAssets(), "fonts/YeZiGongChangZhaoPaiTi-2.ttf");
            textPaint.setTypeface(customFont);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public GameButton(Context context, Rect bounds, String text, int backgroundColor, int pressedBackgroundColor,
                      int textColor, float textSizeSp, int cornerRadius) {
        this.context = context;
        this.bounds = bounds;
        this.text = text;
        this.backgroundColor = backgroundColor;
        this.pressedBackgroundColor = pressedBackgroundColor;
        this.textColor = textColor;
        this.textSizeSp = textSizeSp;
        this.cornerRadius = cornerRadius;

        // 初始化画笔
        paint = new Paint();
        paint.setAntiAlias(true);

        textPaint = new Paint();
        textPaint.setAntiAlias(true);
        textPaint.setTextSize(pxFromSp(textSizeSp));
        textPaint.setColor(textColor);

        // 初始化音效工具类
        soundUtils = new SoundUtils(context);

        // 加载自定义字体
        try {
            Typeface customFont = Typeface.createFromAsset(context.getAssets(), "fonts/YeZiGongChangZhaoPaiTi-2.ttf");
            textPaint.setTypeface(customFont);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置自定义字体
     *
     * @param typeface 字体
     */
    public void setTypeface(Typeface typeface) {
        if (typeface != null) {
            textPaint.setTypeface(typeface);
        }
    }

    /**
     * 设置文字大小
     *
     * @param textSize 文字大小
     */
    public void setTextSize(float textSize) {
        textPaint.setTextSize(textSize);
    }

    /**
     * 检查是否点击了按钮
     *
     * @return 是否点击了按钮
     */
    public boolean handleTouchEvent(MotionEvent event) {
        float x = event.getX();
        float y = event.getY();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (bounds.contains((int) x, (int) y)) {
                    isPressed = true;
                    animateScale(0.9f); // 缩小到90%
                    return false;
                }
                break;
            case MotionEvent.ACTION_UP:
                if (isPressed && bounds.contains((int) x, (int) y)) {
                    // 播放点击音效
                    soundUtils.playSoundClick();
                    if (onClickListener != null) {
                        onClickListener.onClick();
                    }
                    isPressed = false;
                    // 恢复原始大小
                    animateScale(1.0f);
                    return true;
                }
                isPressed = false;
                // 恢复原始大小
                animateScale(1.0f);
                break;
            case MotionEvent.ACTION_CANCEL:
                isPressed = false;
                // 恢复原始大小
                animateScale(1.0f);
                break;
        }
        return false;
    }

    public boolean contains(MotionEvent event) {
        return this.bounds.contains((int) event.getX(), (int) event.getY());
    }

    /**
     * 绘制按钮
     *
     * @param canvas 画布
     */
    public void draw(Canvas canvas) {
        // 保存画布状态
        canvas.save();

        // 计算缩放中心点
        float centerX = bounds.left + bounds.width() / 2f;
        float centerY = bounds.top + bounds.height() / 2f;

        // 应用缩放变换
        canvas.scale(scaleFactor, scaleFactor, centerX, centerY);

        // 绘制背景（仅当设置了背景色时）
        if (backgroundColor != 0 || pressedBackgroundColor != 0) {
            paint.setColor(isPressed ? pressedBackgroundColor : backgroundColor);
            canvas.drawRoundRect(bounds.left, bounds.top, bounds.right, bounds.bottom, cornerRadius, cornerRadius, paint);
        }

        // 绘制文字
        if (text != null && !text.isEmpty()) {
            float textWidth = textPaint.measureText(text);
            float textX = bounds.left + (bounds.width() - textWidth) / 2;
            float textY = bounds.top + (bounds.height() + getTextHeight()) / 2;
            canvas.drawText(text, textX, textY, textPaint);
        }

        // 恢复画布状态
        canvas.restore();
    }

    /**
     * 获取文字高度
     *
     * @return 文字高度
     */
    private float getTextHeight() {
        android.graphics.Rect bounds = new android.graphics.Rect();
        textPaint.getTextBounds("A", 0, 1, bounds);
        return bounds.height();
    }

    /**
     * 获取按钮边界
     *
     * @return 按钮边界
     */
    public Rect getBounds() {
        return bounds;
    }

    /**
     * 设置按钮边界
     *
     * @param bounds 按钮边界
     */
    public void setBounds(Rect bounds) {
        this.bounds = bounds;
    }

    /**
     * 设置按钮文字
     *
     * @param text 按钮文字
     */
    public void setText(String text) {
        this.text = text;
    }

    /**
     * 设置背景颜色
     *
     * @param backgroundColor 背景颜色
     */
    public void setBackgroundColor(int backgroundColor) {
        this.backgroundColor = backgroundColor;
    }

    /**
     * 设置文字颜色
     *
     * @param textColor 文字颜色
     */
    public void setTextColor(int textColor) {
        this.textColor = textColor;
        textPaint.setColor(textColor);
    }

    /**
     * 执行缩放动画
     *
     * @param targetScale 目标缩放比例
     */
    private void animateScale(float targetScale) {
        if (scaleAnimator != null && scaleAnimator.isRunning()) {
            scaleAnimator.cancel();
        }

        scaleAnimator = ValueAnimator.ofFloat(scaleFactor, targetScale);
        scaleAnimator.setDuration(100); // 动画持续时间100毫秒
        scaleAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                scaleFactor = (float) animation.getAnimatedValue();
            }
        });
        scaleAnimator.start();
    }
}